// pages/my/settle/index.js
const app = getApp()
const { baseURL } = require('../../../fetch/http')
const api = require('../../../fetch/api')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL: baseURL,
    total: 0, // 总计
    num: 0 , // 购买数量
    show: false,
    title:"微信支付",
    actions: [
      {
        name: '微信支付',
      },
      {
        name: '余额支付',
      }
    ],
  }, 
  payStatus(){
    this.setData({
      show:true
    })
  },
  onSelect(e){
    var title=e.detail.name;
    this.setData({
      title:title,
      show:false
    })
  },
  async address() {
    let res = await api.address()
    let arr = res.data
    if(arr.length>0) {
      this.setData({
        address: arr[0]
      })
    }
  }, 
  async pay() {
    let res = await api.buy({
      cart_id: this.data.id.split(','),
      address_id: this.data.address.id,
      pay_type:this.data.title=='微信支付'?'1':'2'
    })
    api.wxpay(res.data).then(res => {
      // console.log(res);
      if (res.errMsg == "requestPayment:ok") {
        app.toast('支付成功','success',()=>{
          wx.navigateTo({
            url: '/pages/my/orders/index',
          })
        })
      }
    }).catch(error => {
      console.log(error);
    })
  },
  
  reduce() {
    let { num } = this.data
    num > 1 && num--
    this.setData({
      num
    })
  },
  add() {
    let { num, spec } = this.data
    num < spec.sku && num++
    this.setData({
      num
    })
  },
  chooseAddress() {
    wx.navigateTo({
      url: '/pages/my/address/index?flag=true',
    })
  },
  async address() {
    let res = await api.address()
    let arr = res.data
    if(arr.length>0) {
      this.setData({
        address: arr[0]
      })
    }
  },
  async submit() {
    let res = await api.submit({
      cart_id: this.data.id.split(','),
    })
    
    let {goods,expressFee,payMoney,saleMoney,totalMoney} = res.data
    this.setData({
      goods,expressFee,payMoney,saleMoney,totalMoney
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      num: options.num
    })
    this.submit()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let { address } = app.globalData
    if(address.province){
      this.setData({
        address
      })
    }else {
      this.address()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})